﻿namespace S4sme.Tasks.Blog
{
    using System.Linq;

    using S4sme.Domain;
    using S4sme.Tasks.Blog.ViewModels;

    using SharpLite.Domain.DataInterfaces;

    /// <summary>
    /// Create - Update - Delete tasks for Category
    /// </summary>
    public class CategoryCudTasks : BaseEntityCudTasks<Category, EditCategoryViewModel>
    {
        private readonly IRepository<Category> categoryRepository;

        public CategoryCudTasks(IRepository<Category> categoryRepository)
            : base(categoryRepository)
        {
            this.categoryRepository = categoryRepository;
        }

        /// <summary>
        /// Basic view model factory which initializes lists for dropdowns and adds any security
        /// details to the view model (e.g., .MayAddAttachments) if appropriate.
        /// We can't use the CreateEditViewModel() from the base class because we need to add
        /// categories to the view model which will be shown in a dropdown list.
        /// </summary>
        /// <returns>
        /// The create edit view model.
        /// </returns>
        public override EditCategoryViewModel CreateEditViewModel() 
        {
            var viewModel = base.CreateEditViewModel();

            // These will be displayed by the view to optionally select a parent category
            viewModel.AvailableCategories = this.categoryRepository.GetAll().OrderBy(pc => pc.Name);

            return viewModel;
        }

        /// <summary>
        /// We need to replace the base class' version of this because we need to modify the product
        /// category listing before it gets passed to the view.
        /// </summary>
        /// <param name="category">
        /// The category.
        /// </param>
        /// <returns>
        /// The create edit view model.
        /// </returns>
        public override EditCategoryViewModel CreateEditViewModel(Category category) 
        {
            var viewModel = this.CreateEditViewModel();
            viewModel.Category = category;

            // Don't allow a category to have itself as a parent
            viewModel.AvailableCategories = viewModel.AvailableCategories.Where(pc => !pc.Equals(category));

            return viewModel;
        }

        /// <summary>
        /// Udpates an entitry from the DB with new information from the form.  This example 
        /// manually copies the data but you could use a more sophisticated mechanism, like AutoMapper
        /// </summary>
        /// <param name="toUpdate">
        /// The to Update.
        /// </param>
        /// <param name="fromForm">
        /// The from Form.
        /// </param>
        protected override void TransferFormValuesTo(Category toUpdate, Category fromForm) 
        {
            toUpdate.Name = fromForm.Name;
            toUpdate.Parent = fromForm.Parent;
        }
    }
}
